const express = require('express');
const router = express.Router();
const Role = require('../models/role');
const Counter = require('../models/counter');

// 创建部门
router.post("/role", async (req, res) => {
    //使用Hero model上的create方法储存数据
    try {
        const { roleName, permissionCharacters, order, menuIds, remark, state } = req.body;
        const counter = await Counter.findOneAndUpdate(
            { _id: 'roleCode' }, // 序列标识
            { $inc: { seq: 1 } },
            { new: true, upsert: true } // 不存在时自动创建
        );
        const role = new Role({ roleCode: counter.seq, roleName, permissionCharacters, order, menuIds, remark, state })
        await role.save();
        res.send({ message: "操作成功" })
    } catch (err) {
        // 如果有错误，返回错误信息  
        res.status(500).json({ error: err.message });
    }
});
// 查询部门
router.get("/role", async (req, res) => {
    try {
        const filter = {};
        if (req.query.roleName) {
            filter.roleName = { $regex: req.query.roleName, $options: 'i' };
        }
        if (req.query.state) {
            filter.state = req.query.state;
        }
        if (req.query.permissionCharacters) {
            filter.permissionCharacters = req.query.permissionCharacters;
        }
        if (req.query.createdAt) {
            filter.createdAt = { $gte: JSON.parse(req.query.createdAt)[0], $lte: JSON.parse(req.query.createdAt)[1] };
        }
        const currentPage = parseInt(req.query.currentPage) || 1;
        const limit = parseInt(req.query.pageSize) || 10;
        const skip = (currentPage - 1) * limit;
        const role = await Role.find(filter).skip(skip).limit(limit);
        const total = await Role.countDocuments(filter);
        res.send({ page: { total, currentPage, pageSize: limit }, result: role });
    } catch (err) {
        res.status(500).send({ error: err });
    }
});
// 编辑部门
router.put("/role", async (req, res) => {
    try {
        const updatedRole = await Role.findByIdAndUpdate(req.body.id, req.body, { new: true });
        if (!updatedRole) return res.status(404).send({ error: 'Hero not found' });
        res.send({ message: "操作成功" });
    } catch (err) {
        res.status(500).send({ error: err });
    }
});
//删除部门
router.delete("/role", async (req, res) => {
    try {
        // 从查询参数中获取id
        const id = req.query.id;
        if (!id) {
            return res.status(400).send({ error: 'Missing "id" query parameter' });
        }
        await Role.findByIdAndDelete(id);
        res.send({ message: '操作成功' });
    } catch (err) {
        if (err.name === 'CastError') return res.status(404).send({ error: 'Hero not found' });
        res.status(500).send({ error: '操作失败' });
    }
});
module.exports = router